import 'dart:convert';
import 'package:base_flutter/base_flutter.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:ls_work/a_yyt/models/medical_elder_entity.dart';
import 'package:ls_work/a_yyt/models/pending_selected_group_entity.dart';
import 'package:ls_work/a_yyt/page/health_file_page.dart';
import 'package:ls_work/mvp/svp_progress.dart';
import 'package:ls_work/net/HttpUtil.dart';
import 'package:ls_work/net/net.dart';
import 'package:ls_work/net/post_request.dart';
import 'package:ls_work/res/colors.dart';
import 'package:ls_work/res/gaps.dart';
import 'package:ls_work/res/styles.dart';
import 'package:ls_work/util/app_navigator.dart';
import 'package:ls_work/util/toast.dart';
import 'package:ls_work/widgets/my_refresh_divider_list.dart';

import '../../util/flat_button.dart';



class MedicalHistoryPage extends StatefulWidget {
  final MedicalElderInfo? info;
  MedicalHistoryPage({Key? key, this.info});
  @override
  _MedicalHistoryPageState createState() => _MedicalHistoryPageState();
}

class _MedicalHistoryPageState extends State<MedicalHistoryPage> {
  PendingSelectedGroupEntity? info;
  List<PendingSelectedGroupEntity> chipMedicalList = [];
  List<PendingSelectedGroupEntity> chipDateList = [];
  List<PendingSelectedGroupEntity> chipeErrorList = [];
  int _page = 1;
  List<MedicalElderInfo> dataList = [];
  int medcialId = 0;
  int queryTimeType = 0;
  int? errorId;
  bool isMore = false;

  @override
  void initState() {
    chipMedicalList = [
      PendingSelectedGroupEntity(isSelected: true, id: 0, name: '全部'),
      PendingSelectedGroupEntity(isSelected: false, id: 7, name: '血压'),
      PendingSelectedGroupEntity(isSelected: false, id: 4, name: '血氧'),
      PendingSelectedGroupEntity(isSelected: false, id: 5, name: '心率'),
      PendingSelectedGroupEntity(isSelected: false, id: 6, name: '体温'),
      PendingSelectedGroupEntity(isSelected: false, id: 11, name: '血糖'),
      PendingSelectedGroupEntity(isSelected: false, id: 2, name: '体重'),
      PendingSelectedGroupEntity(isSelected: false, id: 19, name: '饮水'),
      PendingSelectedGroupEntity(isSelected: false, id: 20, name: '尿量'),
    ];
    chipDateList = [
      PendingSelectedGroupEntity(isSelected: true, id: 0, name: '昨天'),
      PendingSelectedGroupEntity(isSelected: false, id: 1, name: '今天'),
      PendingSelectedGroupEntity(isSelected: false, id: 2, name: '近7天'),
      PendingSelectedGroupEntity(isSelected: false, id: 3, name: '近14天'),
      PendingSelectedGroupEntity(isSelected: false, id: 4, name: '近30天'),
    ];
    chipeErrorList = [
      PendingSelectedGroupEntity(isSelected: true, id: 0, name: '全部'),
      PendingSelectedGroupEntity(isSelected: false, id: 1, name: '异常'),
    ];
    WidgetsBinding.instance.addPostFrameCallback((_) {
      /// 接口请求
      _fectData();
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('${widget.info?.name??""} ${widget.info?.roomNo??""}'),
        elevation: 0.5,
        actions: [
          FlatsButton(
            onPressed: () {
              Navigator.pop(context);
            },
            child: Text(
              '登记',
              style: TextStyle(fontSize: 16, color: Colours.app_main),
            ),
          )
        ],
      ),
      body: Container(
        padding: EdgeInsets.only(left: 20, right: 20),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Wrap(
              spacing: 10,
              children: (chipMedicalList??[]).map(
                (f) {
                  return ChoiceChip(
                    label: Text(f.name??""),
                    selected: f.isSelected==true,
                    selectedColor: Colours.app_main,
                    disabledColor: Colours.bg_color,
                    onSelected: (bool value) {
                      setState(
                        () {
                          if (value) {
                            for (var item in chipMedicalList) {
                              if (item.id == f.id) {
                                item.isSelected = true;
                                medcialId = item.id??0;
                                _onRefresh();
                              } else {
                                item.isSelected = false;
                              }
                            }
                          }
                        },
                      );
                    },
                  );
                },
              ).toList(),
            ),
            Wrap(
              spacing: 10,
              children: chipDateList.map(
                (f) {
                  return ChoiceChip(
                    label: Text(f.name??""),
                    selected: f.isSelected==true,
                    selectedColor: Colours.app_main,
                    disabledColor: Colours.bg_color,
                    onSelected: (bool value) {
                      setState(
                        () {
                          if (value) {
                            for (var item in chipDateList) {
                              if (item.id == f.id) {
                                item.isSelected = true;
                                queryTimeType = item.id??0;
                                _onRefresh();
                              } else {
                                item.isSelected = false;
                              }
                            }
                          }
                        },
                      );
                    },
                  );
                },
              ).toList(),
            ),
            Wrap(
              spacing: 10,
              children: chipeErrorList.map(
                (f) {
                  return ChoiceChip(
                    label: Text(f.name??""),
                    selected: f.isSelected==true,
                    selectedColor: Colours.app_main,
                    disabledColor: Colours.bg_color,
                    onSelected: (bool value) {
                      setState(
                        () {
                          if (value) {
                            for (var item in chipeErrorList) {
                              if (item.id == f.id) {
                                item.isSelected = true;
                                errorId = item.id;
                                _onRefresh();
                              } else {
                                item.isSelected = false;
                              }
                            }
                          }
                        },
                      );
                    },
                  );
                },
              ).toList(),
            ),
            Expanded(
              child: DeerSeparatedListView(
                onRefresh: _onRefresh,
                loadMore: _loadMore,
                hasMore: isMore,
                itemCount: dataList.length,
                itemBuilder: (context, index) {
                  return InkWell(
                    onTap: () {},
                    child: Container(
                      padding: EdgeInsets.fromLTRB(15, 20, 15, 20),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          Text(
                            (dataList[index].dataType??"").contains("压")
                                ? "血压"
                                : '${dataList[index].dataType}',
                            style: TextStyles.textDark20,
                          ),
                          Gaps.hGap15,
                          Text(
                            '${dataList[index].numberConcat}',
                            style: TextStyles.textGray18,
                          ),
                          Gaps.hGap15,
                          Gaps.hGap15,
                          Text(
                            '${dataList[index].collectionTime}${dataList[index].sourceName}',
                            style: TextStyles.textGray18,
                          ),
                        ],
                      ),
                    ),
                  );
                },
                separatorBuilder: (_, index) => Gaps.line,
              ),
            ),
            Container(
              padding: EdgeInsets.only(bottom: 20),
              height: 70,
              width: double.infinity,
              child: FlatsButton(
                child: Text(
                  "趋势变化",
                  style: TextStyle(fontSize: 18, color: Colors.white),
                ),
                shape: StadiumBorder(),
                color: Colours.app_main,
                onPressed: () {
                  AppNavigator.push(
                    context,
                    HealthFilePage(
                      info: widget.info,
                    ),
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  _fectData() {
    var map = {
      'page': _page,
      'rows': 20,
      'customerId': widget.info?.id,
      'dataTypeId': medcialId == 0 ? '' : medcialId,
      'queryTimeType': queryTimeType,
      // 'orderByDesc': isUpSort,
    };

    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    HttpUtil.instance
        .getDio()
        .post('${HttpApi.getHealthRecord}', data: map,options: PostRequest.urlencodedHeader)
        .then((r) {
      ///
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        //
        if (map["code"].toString() == "0") {
          if (map['data'] != null) {
            MedicalElderModel model = MedicalElderModel.fromJson(map['data']);
            if ((model.rows??[]).length > 0) {
              isMore = ((model.rows??[]).length == 20);
              setState(() {
                if (_page == 1) {
                  /// 刷新
                  dataList.clear();
                  dataList.addAll(model.rows??[]);
                } else {
                  dataList.addAll(model.rows??[]);
                }
              });
            } else {
              if (_page == 1) {
                /// 刷新
                setState(() {
                  dataList.clear();
                  dataList.addAll(model.rows??[]);
                });
              }
              Toast.show("没有更多数据");
            }
          } else {
            Toast.show(map["msg"]);
          }
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }

  Future _onRefresh() async {
    _page = 1;
    await _fectData();
  }

  Future _loadMore() async {
    _page++;
    await _fectData();
  }
}
